package com.cenxi.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;


@Slf4j
@Component
public class OssUploadUtils {
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucketName}")
    private String bucketName;

    public String uploadFile(MultipartFile file) {
        String uploadName = uploadImgName();
        String objectName = "service/" + uploadName + "-" + file.getOriginalFilename();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(file.getContentType());
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream(), objectMetadata);
            // 上传文件。
            ossClient.putObject(putObjectRequest);
            return putObjectRequest.getKey();
        } catch (OSSException oe) {
            log.error("上传失败, {}", oe.getMessage());
        } catch (ClientException | IOException ce) {
            log.error("上传失败, {}", ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "null";
    }

    public Boolean deleteFile(String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, fileName.split("/", 4)[3]);
            return true;
        } catch (OSSException oe) {
            log.error("删除失败, {}", oe.getMessage());
        } catch (ClientException ce) {
            log.error("删除失败, {}", ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return false;
    }

    public static String uploadImgName() {
        return UUID.randomUUID() + "-" + System.currentTimeMillis();
    }

}
